package com.request.service.impl.shop.kx;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.request.common.constants.RedisConstant;
import com.request.common.enums.KxDistributeOrderStatusEnum;
import com.request.common.enums.RechargeTypeEnum;
import com.request.common.utils.HttpUtils;
import com.request.entity.PhoneOrderWaitCheck;
import com.request.service.QueryOrderProcessor;
import com.request.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Description:
 * Create DateTime: 2020-04-23 10:43
 *
 * 

 */
@Slf4j
@Service
public class KxDistributeQueryOrderProcessor implements QueryOrderProcessor {

    @Resource
    private RedisService redisService;
    @Resource
    private ThreadPoolExecutor handlerOrderExecutor;

    @Override
    public void sendRequest(PhoneOrderWaitCheck orderWaitCheck) {
        handlerOrderExecutor.execute(() -> executeWaitOrderQuery(orderWaitCheck));
    }

    /**
     * 执行待查询订单查询
     *
     * @param phoneOrderWaitCheck 待查询订单
     */
    private void executeWaitOrderQuery(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        Map<String, Object> params = new HashMap<>(3);
        String result = null;
        try {
            String querySite = phoneOrderWaitCheck.getQuerySite();

            params.put("orderNo", phoneOrderWaitCheck.getPlatformOrderNo());
            params.put("appId", phoneOrderWaitCheck.getAppId());
            String sb = phoneOrderWaitCheck.getAppKey() +
                    phoneOrderWaitCheck.getAppId() +
                    phoneOrderWaitCheck.getPlatformOrderNo() +
                    phoneOrderWaitCheck.getAppKey();
            String sign = SecureUtil.sha256(sb);
            params.put("sign", sign);

            log.info("【魁信配单】查询参数:{},查询地址:{}", params, querySite);
            result = sendRequestForWaitOrder(querySite, params);
            log.info("【魁信配单】查询返回结果:{}", result);
            JSONObject jsonResult = JSON.parseObject(result);
            String code = jsonResult.getString("code");

            if (code.equals("2")) {
                phoneOrderWaitCheck.setStatus(0);
                saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                return;
            }
            JSONObject data = jsonResult.getJSONObject("data");
            String orderStatus = data.getString("orderStatus");
            String shopOrderNo = data.getString("shopOrderNo");
            String orderSn = data.getString("orderSn");
            String certificate = data.getString("certificate");
            String detailMessage = data.getString("detailMessage");
            phoneOrderWaitCheck.setShopOrderNo(shopOrderNo);
            phoneOrderWaitCheck.setOrderSn(orderSn);
            phoneOrderWaitCheck.setStatus(Integer.valueOf(orderStatus).equals(1) ? 1 : 0);
            phoneOrderWaitCheck.setMessage(detailMessage);
            phoneOrderWaitCheck.setCertificate(certificate);

            KxDistributeOrderStatusEnum statusEnum = KxDistributeOrderStatusEnum.getByCode(orderStatus);
            if (null == statusEnum) {
                throw new RuntimeException("响应code为：" + code);
            }
            switch (statusEnum) {
                case SUCCESS:
                case FAILED:
                    saveWaitOrderQueryForSuccess(phoneOrderWaitCheck);
                    break;
                case PROCESSING:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
                default:
                    saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
                    break;
            }

        } catch (Exception e) {
            saveWaitOrderQueryForProcessing(phoneOrderWaitCheck);
            log.error("【魁信配单】【超时检查】请求商户出现异常，待检查订单信息为：{}, 参数为：{}, 商户响应信息为:{}, 错误详情为：",
                    phoneOrderWaitCheck, params.toString(), result, e);
        }
    }

    /**
     * 发送Http请求
     *
     * @param url    请求路径
     * @param params 参数
     * @return 响应结果
     */
    private String sendRequestForWaitOrder(String url, Map<String, Object> params) {
        String paramJson = JSON.toJSONString(params);
        return HttpUtils.jsonPost(url, paramJson);
    }

    /**
     * 放入成功队列
     */
    private void saveWaitOrderQueryForSuccess(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_SUCCESS, JSON.toJSONString(phoneOrderWaitCheck));
    }

    /**
     * 放入失败队列
     */
    private void saveWaitOrderQueryForFailed(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_FAILED, JSON.toJSONString(phoneOrderWaitCheck));
    }

    /**
     * 放入处理中队列
     */
    private void saveWaitOrderQueryForProcessing(PhoneOrderWaitCheck phoneOrderWaitCheck) {
        if (!RechargeTypeEnum.SLOW.getCode().equals(phoneOrderWaitCheck.getRechargeType())) {
            redisService.lPush(RedisConstant.PUSH_ORDER_WAIT_CHECK_PROCESSING, JSON.toJSONString(phoneOrderWaitCheck));
        }
    }
}
